package com.xmall.auth.controller;

import com.xmall.annotation.LoginRequiredFalse;
import com.xmall.auth.define.request.PhonePasswordLoginRequest;
import com.xmall.auth.service.ILoginService;
import com.xmall.define.base.Result;
import com.xmall.define.base.ResultCode;
import com.xmall.define.dto.login.MemberLoginInfo;
import com.xmall.define.dto.login.SysLoginInfo;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 登录登出
 */
@RequestMapping("/service/auth")
@RestController
public class LoginController {

    @Resource
    private ILoginService loginService;

    /**
     * 是否处于登录状态
     */
    @LoginRequiredFalse
    @PostMapping("/isLogin")
    public Result<Boolean> isLogin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return Result.success(authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken));
    }

    /**
     * 系统用户：手机号 + 密码登录
     */
    @LoginRequiredFalse
    @PostMapping("/sys/loginWithPhonePassword")
    public Result<SysLoginInfo> sysLoginWithPhonePassword(@RequestBody PhonePasswordLoginRequest request){
        SysLoginInfo account = loginService.sysLoginWithPhonePassword(request);
        return null == account ? Result.error(ResultCode.AUTH_LOGIN_ERROR) : Result.success(account);
    }

    /**
     * 普通用户：手机号 + 密码登录
     */
    @LoginRequiredFalse
    @PostMapping("/member/loginWithPhonePassword")
    public Result<MemberLoginInfo> memberLoginWithPhonePassword(@RequestBody PhonePasswordLoginRequest request){
        MemberLoginInfo account = loginService.memberLoginWithPhonePassword(request);
        return null == account ? Result.error(ResultCode.AUTH_LOGIN_ERROR) : Result.success(account);
    }

}
